package com.example.smartcity_poverty.ui.AllService.SmartBus.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import com.example.smartcity_poverty.App.Companion.getToken
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.Repository.coroutine
import com.example.smartcity_poverty.logic.util.Util
import com.example.smartcity_poverty.logic.util.Util.show
import kotlinx.android.synthetic.main.activity_smart_bus_four.*
import kotlinx.coroutines.Dispatchers
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

class SmartBusFourActivity : AppCompatActivity() {

    private val id by lazy { intent.getStringExtra("id")?.toInt() }
    private val time by lazy { intent.getStringExtra("time")?.toString() }
    private val tv1 by lazy { intent.getStringExtra("tv1")?.toString() }
    private val tv2 by lazy { intent.getStringExtra("tv2")?.toString() }
    private val tv3 by lazy { intent.getStringExtra("tv3")?.toString() }
    private val tv4 by lazy { intent.getStringExtra("tv4")?.toString() }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_smart_bus_four)
        title = "确认信息"

        Util.addActivity(this)

        busFour1.text = "姓名: $tv1"
        busFour2.text = "手机号码: $tv2"
        busFour3.text = "上车地点: $tv3"
        busFour4.text = "下车地点: $tv4"
        busFour5.text = "乘车日期: $time"


        busFourOk.setOnClickListener {
            if (getToken().isNotEmpty()){
                // 提交订单
                coroutine(Dispatchers.IO){

                    val data = api.getBusPathDataIls(id!!)

                    val result = api.getBusPost(getToken(), JSONObject().apply {
                        put("start", tv3.toString())
                        put("end", tv4.toString())
                        put("path", data.data?.name.toString())
                        put("price", data.data?.price.toString())
                        put("status", "1")
                    }.toString().toRequestBody("application/json".toMediaTypeOrNull()))

                    if (result.code == "200"){
                        runOnUiThread {
                            result.msg.show()
                            // 删除所有的Activity
                            Util.removeActivity()
                        }
                    }else runOnUiThread { result.msg.show() }
                }
            }

        }

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}